/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.ContributoryPlanBean;
import com.koron.purpose.bean.ContributoryPlanBeanDetail;
import com.koron.purpose.mapper.ContributoryPlanMapper;
import com.koron.purpose.service.api.ContributoryPlanService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.purpose.utils.PdfFileUtil;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.math.BigDecimal;
import java.util.*;

@SuppressWarnings("deprecation")
@Service
@PropertySource({"classpath:flow.properties"})
public class ContributoryPlanServiceImpl implements ContributoryPlanService, AfterApprovalService, InitializingBean {
    // 状态标记(0-审批中 1-审批通过 2-草稿)
    private final String STATUS_FLAG_0 = "0";
    // 状态标记(0-审批中 1-审批通过 2-草稿)
    private final String STATUS_FLAG_1 = "1";
    // 状态标记(0-审批中 1-审批通过 2-草稿)
    private final String STATUS_FLAG_2 = "2";

    private final static Logger logger= LoggerFactory.getLogger(ContributoryPlanServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Value("${conPlan_template_key}")
    private String templateKey;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private PdfFileUtil pdfFileUtil;

    @Override
    public void editApproval(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
                    JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                    JobsTasks jobsTasks = null;
                    String otherId = Optional.ofNullable(audit.getOtherBusinessIds()).orElse("").replaceAll("\"", "");
                    if (!StringUtils.isEmpty(otherId)) {
                        jobsTasks = jobsTasksMapper.queryById(otherId);
                    }
                    for (String id : ids) {
                        if (mapper.updateConPlanStatusById(id, STATUS_FLAG_1) != 1) {
                            factory.close(false);
                            return null;
                        }
                        // 判断 该业务是否 是工作任务的业务数据，如果是，则修改工作任务
                        if (jobsTasks != null) {
                            // 完成日期
                            Date completedTime = jobsTasks.getCompletedTime();
                            // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                            int state;
                            if (jobsTasks.getEndTime() == null || jobsTasks.getEndTime().after(completedTime)) {
                                state = 1;
                            } else {
                                state = 2;
                            }
                            // 流程状态：0草稿 1审批中 2审批通过
                            int fstatusflag = 2;
                            JobsTasks updateJob = new JobsTasks();
                            updateJob.setId(jobsTasks.getId());
                            updateJob.setState(state);
                            updateJob.setFstatusflag(fstatusflag);
                            updateJob.setCompletedTime(completedTime);
                            // 业务id
                            updateJob.setBusinessId(id);
                            if (jobsTasksMapper.completed(updateJob) != 1) {
                                factory.close(false);
                                return null;
                            }
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        Optional.ofNullable(audit)
                .map(obj -> obj.getBusinessIds())
                .map(ids -> {
                    List<String> list = JSON.parseArray(ids, String.class);
                    return Optional.ofNullable(list);
                }).map(idsList -> {
            List<String> idList = idsList.get();
            Optional.ofNullable(idList).map(ids -> {
                SessionFactory factory = new SessionFactory();
                try {
                    ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
                    JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                    JobsTasks jobsTasks = null;
                    String otherId = Optional.ofNullable(audit.getOtherBusinessIds()).orElse("").replaceAll("\"", "");
                    if (!StringUtils.isEmpty(otherId)) {
                        jobsTasks = jobsTasksMapper.queryById(otherId);
                    }
                    for (String id : ids) {
                        if (mapper.updateConPlanStatusById(id, STATUS_FLAG_2) != 1) {
                            factory.close(false);
                            return null;
                        }
                        // 判断 该业务是否 是工作任务的业务数据，如果是，则修改工作任务 为代办
                        if (jobsTasks != null) {
                            // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                            int state = 3;
                            // 流程状态：0草稿 1审批中 2审批通过
                            int fstatusflag = 0;
                            JobsTasks updateJob = new JobsTasks();
                            updateJob.setId(jobsTasks.getId());
                            updateJob.setState(state);
                            updateJob.setFstatusflag(fstatusflag);
                            updateJob.setCompletedTime(null);
                            // 业务id
                            updateJob.setBusinessId(id);
                            if (jobsTasksMapper.completed(updateJob) != 1) {
                                factory.close(false);
                                return null;
                            }
                        }
                    }
                    factory.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    factory.close(false);
                }
                return null;
            });
            return null;
        });
    }

    @Override
    public MessageBean<DataBean<Map>> queryForList(String corpCode, Integer year, String manager, String statusFlag, Integer page, Integer pageSize, String keyword) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("corpCode", corpCode);
            map.put("year", year);
            map.put("manager", manager);
            page = (page == null || page < 1) ? 1 : page;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
            int pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            // 查询 状态标记(0-审批中 1-审批通过 2-草稿) 不为审批中的数据
            map.put("status_flag_0", STATUS_FLAG_0);
            map.put("status_flag", statusFlag);
            map.put("keyword",keyword);
            List<Map> list = mapper.queryForList(map);
            DataBean<Map> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            // 总条数
            Integer totalNumber = mapper.countQueryForList(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<Map> queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            // 查询
            Map bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("未查到该投入计划");
            } else {
                List<ContributoryPlanBeanDetail> list = mapper.getDetailById(id);
                bean.put("details", list);
                msg.setData(bean);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            Map bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该使用计划已被删除");
                factory.close(false);
                return msg;
            } else if (!STATUS_FLAG_2.equals(bean.get("statusFlag").toString())) {// 草稿可删除和编辑，非草稿不可删除和编辑
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("当前使用计划不为草稿，不能进行删除");
                factory.close(false);
                return msg;
            }
            // 根据id 删除 投入计划
            int i = mapper.deletePlan(id);
            if (i != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("删除失败!");
                factory.close(false);
            } else {
                mapper.deleteDetailsByConId(id);
                factory.close();
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean insert(StaffBean user, ContributoryPlanBean bean,
                              String details, MultipartFile[] files, String jobsTasksId, String personCodes) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        if (bean.getYear() == 0 || StringUtils.isEmpty(bean.getManager())
                || StringUtils.isEmpty(bean.getManagerName()) || StringUtils.isEmpty(bean.getSerialNumber())
                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
        ) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            // 新增 附件
            String fileMsgs = saveFiles(files);
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            // 新增 安全活动台账表
            BigDecimal planMoney = new BigDecimal(0);
            List<ContributoryPlanBeanDetail> list = null;
            if (!StringUtils.isEmpty(details)) {
                list = JSON.parseArray(details, ContributoryPlanBeanDetail.class);
                // 参数校验，并计算总额
                for (ContributoryPlanBeanDetail planBeanDetail : list) {
                    if (StringUtils.isEmpty(planBeanDetail.getContributoryProject())
                            || StringUtils.isEmpty(planBeanDetail.getContributoryProjectName())) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("投入项目不能为空!");
                        return msg;
                    }
                    if (planBeanDetail.getTime() == null) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("计划投入时间不能为空!");
                        return msg;
                    }
                    if (planBeanDetail.getPlanMoney() == null) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("计划投入金额不能为空!");
                        return msg;
                    }
                    if (StringUtils.isEmpty(planBeanDetail.getPersonCharge())
                            || StringUtils.isEmpty(planBeanDetail.getPersonChargeName())) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("责任人不能为空!");
                        return msg;
                    }
                    planMoney = planMoney.add(planBeanDetail.getPlanMoney());
                }
            }
            // 设定最大金额
            BigDecimal maxMoney = new BigDecimal(999999999.99);
            if (planMoney.compareTo(maxMoney) > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("金额过大!");
                return msg;
            }
            // 计划金额
            bean.setPlanMoney(planMoney);
            // 实际金额
            bean.setRealityMoney(new BigDecimal(0));
            bean.setAccessorys(fileMsgs);

            Date date = new Date();
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setAddTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(date);
            String id = DefaultIdGenerator.getInstance().generateLongId();
            bean.setId(id);
            // 使用台账状态(0-未提交 1-审批中 2-审批通过)
            bean.setDetailStatusFlag("0");
            mapper.insert(bean);
            // 判断 状态标记(0-审批中 1-审批通过 2-草稿) 是否为审批中，如果不为，则为草稿
            if (!STATUS_FLAG_0.equals(bean.getStatusFlag())) {
                bean.setStatusFlag(STATUS_FLAG_2);
            }
            // 新增 投入计划明细
            insertDetail(list, id, mapper);

            // 如果 工作任务id 不为空，update 工作任务，将业务主键id修改到任务记录中
            if (STATUS_FLAG_0.equals(bean.getStatusFlag()) && !StringUtils.isEmpty(jobsTasksId)) {
                JobsTasks jobsTasks = new JobsTasks();
                jobsTasks.setId(jobsTasksId);
                jobsTasks.setBusinessId(id);
                jobsTasks.setState(0);
                jobsTasks.setCompletedTime(new Date());
                // -1废弃，0待办，1完成，2延时完成，3执行中
                jobsTasks.setFstatusflag(3);
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                if (jobsTasksMapper.completed(jobsTasks) != 1) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效,请刷新页面!");
                    return msg;
                }
            }

            // 如果状态标记(0-审批中 1-审批通过 2-草稿) 为审批中，则启动流程
            if (STATUS_FLAG_0.equals(bean.getStatusFlag())) {
                if (StringUtils.isEmpty(personCodes)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("各部门审核负责人信息不能为空!");
                    return msg;
                }
                Audit audit = new Audit("投入计划", "投入计划审批", user.getName(), new Date());
                audit.setTitle("投入计划");
                audit.setDescription("投入计划审批");
                audit.setCorpCode(bean.getCorpCode());
                audit.setCorpName(bean.getCorpName());

                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setInitiatorCode(user.getCode());
                audit.setTarget(this.getClass().getName());
                audit.setTemplateKey("contributory_plan");
//                audit.setTemplateKey(templateKey);
                audit.setSetCode("target_duty");
                audit.setInitiatorAccount(user.getUserid());
                audit.setOperation(1);
                audit.setState(1);
                audit.setFlowType(1);
                audit.setFlowName("投入计划审批");
                List<String> idList = Arrays.asList(id);
                audit.setBusinessIds(new Gson().toJson(idList));
                if (!StringUtils.isEmpty(jobsTasksId)) {
                    audit.setOtherBusinessIds(new Gson().toJson(jobsTasksId));
                }
                Map map = new HashMap();
                // 公司各部门负责人（会签）
                List<String> codes = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(personCodes);
                StringBuffer codeStr = new StringBuffer();
                int size = codes.size();
                int count = 0;
                for (String code : codes) {
                    codeStr.append(code);
//                    codeStr.append("1-").append(code);
                    count++;
                    if (count < size) {
                        codeStr.append(",");
                    }
                }
                map.put("personCodes", codeStr.toString());
                // 获取公司 总经理、董事长
//                MessageBean messageBean = corpManagementService.queryPerMsgByCorp(bean.getCorpCode());
//                if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
//                    CorpBean corpBean = (CorpBean) messageBean.getData();
//                    map.put("generalManager", corpBean.getGeneralManager().split("_").length > 1 ? corpBean.getGeneralManager().split("-")[1] : null);
//                    map.put("chairman", corpBean.getChairman().split("_").length > 1 ? corpBean.getChairman().split("_")[1] : null);
//                } else {
//                    factory.close(false);
//                    return messageBean;
//                }
                if (!flowManagement.initFlow(user, audit, map)) {
                    factory.close(false);
                    msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                    msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                    return msg;
                }
            }
            // 关闭
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean update(StaffBean user, ContributoryPlanBean bean, String statusFlag,
                              String details, String accessorys, MultipartFile[] files, String jobsTasksId, String personCodes) {
        MessageBean msg = MessageBean.create(0, "success", void.class);
        SessionFactory factory = new SessionFactory();
        try {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            // 根据id 查询 投入计划
            Map planBean = mapper.queryById(bean.getId());
            if (planBean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该投入计划已经不存在");
                factory.close(false);
                return msg;
            }
            if (!STATUS_FLAG_2.equals(planBean.get("statusFlag").toString())) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("只能修改 草稿 状态的投入计划！");
                factory.close(false);
                return msg;
            }
            List<Map> deleteFileUrls = new LinkedList<>();
            // 删除文件
            String accessoryStr = planBean.get("accessorys") == null ? null : planBean.get("accessorys").toString();
            if (!StringUtils.isEmpty(accessoryStr)) {
                List<Map> accessorys_old = JSON.parseArray(accessoryStr, Map.class);
                List<Map> accessorys_new;
                if (!StringUtils.isEmpty(accessorys)) {
                    accessorys_new = JSON.parseArray(accessorys, Map.class);
                    for (Map map : accessorys_old) {
                        if (!filter(map, accessorys_new, "fileUrl")) {// 不存在:删除文件
                            deleteFileUrls.add(map);
                        }
                    }
                }
            }
            String str = "";
            // 附件保存
            if (files != null) {
                JSONArray array;
                if (!StringUtils.isEmpty(accessorys)) {
                    array = JSON.parseArray(accessorys);
                } else {
                    array = new JSONArray();
                }
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    array.add(object);
                }
                str = JSON.toJSONString(array);
            }
            bean.setAccessorys(str);
            BigDecimal money = new BigDecimal(0);
            List<ContributoryPlanBeanDetail> list = null;
            if (!StringUtils.isEmpty(details)) {
                list = JSON.parseArray(details, ContributoryPlanBeanDetail.class);
                // 参数校验，并计算总额
                for (ContributoryPlanBeanDetail planBeanDetail : list) {
                    if (StringUtils.isEmpty(planBeanDetail.getContributoryProject())
                            || StringUtils.isEmpty(planBeanDetail.getContributoryProjectName())) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("投入项目不能为空!");
                        return msg;
                    }
                    if (planBeanDetail.getTime() == null) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("计划投入时间不能为空!");
                        return msg;
                    }
                    if (planBeanDetail.getPlanMoney() == null) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("计划投入金额不能为空!");
                        return msg;
                    }
                    if (StringUtils.isEmpty(planBeanDetail.getPersonCharge())
                            || StringUtils.isEmpty(planBeanDetail.getPersonChargeName())) {
                        msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                        msg.setDescription("责任人不能为空!");
                        return msg;
                    }
                    money = money.add(planBeanDetail.getPlanMoney());
                }
            }
            // 设定最大金额
            BigDecimal maxMoney = new BigDecimal(999999999.99);
            if (money.compareTo(maxMoney) > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("金额过大!");
                return msg;
            }
            // 计划金额
            bean.setPlanMoney(money);
            bean.setRealityMoney(new BigDecimal(0));
            // 判断 状态标记(0-审批中 1-审批通过 2-草稿) 是否为审批中，如果不为，则为草稿
            if (!STATUS_FLAG_0.equals(bean.getStatusFlag())) {
                bean.setStatusFlag(STATUS_FLAG_2);
            }
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(new Date());
            // 修改 投入计划 信息
            int i = mapper.update(bean);
            if (i != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            // 修改 投入计划明细 信息
            updateDetails(list, bean.getId(), mapper);

            // 如果 工作任务id 不为空，update 工作任务，将业务主键id修改到任务记录中
            if (STATUS_FLAG_0.equals(bean.getStatusFlag()) && !StringUtils.isEmpty(jobsTasksId)) {
                JobsTasks jobsTasks = new JobsTasks();
                jobsTasks.setId(jobsTasksId);
                jobsTasks.setBusinessId(bean.getId());
                jobsTasks.setState(0);
                jobsTasks.setCompletedTime(new Date());
                // -1废弃，0待办，1完成，2延时完成，3执行中
                jobsTasks.setFstatusflag(3);
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                if (jobsTasksMapper.completed(jobsTasks) != 1) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效,请刷新页面!");
                    return msg;
                }
            }

            // 如果状态标记(0-审批中 1-审批通过 2-草稿) 为审批中，则启动流程
            if (STATUS_FLAG_0.equals(bean.getStatusFlag())) {
                if (StringUtils.isEmpty(personCodes)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("各部门审核负责人信息不能为空!");
                    return msg;
                }
                Audit audit = new Audit("投入计划", "投入计划审批", user.getName(), new Date());
                audit.setTitle("投入计划");
                audit.setDescription("投入计划审批");
                audit.setCorpCode(bean.getCorpCode());
                audit.setCorpName(bean.getCorpName());

                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setInitiatorCode(user.getCode());
                audit.setTarget(this.getClass().getName());
                audit.setTemplateKey("contributory_plan");
//                audit.setTemplateKey(templateKey);
                audit.setSetCode("target_duty");
                audit.setInitiatorAccount(user.getUserid());
                audit.setOperation(1);
                audit.setState(1);
                audit.setFlowType(1);
                audit.setFlowName("投入计划审批");
                List<String> idList = Arrays.asList(bean.getId());
                audit.setBusinessIds(new Gson().toJson(idList));
                if (!StringUtils.isEmpty(jobsTasksId)) {
                    audit.setOtherBusinessIds(new Gson().toJson(jobsTasksId));
                }
                Map map = new HashMap();
                // 公司各部门负责人（会签）
                List<String> codes = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(personCodes);
                StringBuffer codeStr = new StringBuffer();
                int size = codes.size();
                int count = 0;
                for (String code : codes) {
                    codeStr.append(code);
//                    codeStr.append("1-").append(code);
                    count++;
                    if (count < size) {
                        codeStr.append(",");
                    }
                }
                map.put("personCodes", codeStr.toString());
                // 获取公司 总经理、董事长
                MessageBean messageBean = corpManagementService.queryPerMsgByCorp(bean.getCorpCode());
                if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
                    CorpBean corpBean = (CorpBean) messageBean.getData();
                    map.put("generalManager", corpBean.getGeneralManager().split("_").length > 1 ? corpBean.getGeneralManager().split("_")[1] : null);
                    map.put("chairman", corpBean.getChairman().split("_").length > 1 ? corpBean.getChairman().split("_")[1] : null);
                } else {
                    factory.close(false);
                    return messageBean;
                }
                if (!flowManagement.initFlow(user, audit, map)) {
                    factory.close(false);
                    msg.setCode(com.koron.hazardsource.util.BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                    msg.setDescription(com.koron.hazardsource.util.BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                    return msg;
                }
            }
            factory.close();
            // 删除文件服务器上的文件
            if (deleteFileUrls != null && deleteFileUrls.size() > 0) {
                for (Map url : deleteFileUrls) {
                    Optional.ofNullable(url.get("fileUrl")).ifPresent(u -> {
                        if (!org.springframework.util.StringUtils.isEmpty(u.toString())) {
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                    Optional.ofNullable(url.get("pdfUrl")).ifPresent(u -> {
                        if (!org.springframework.util.StringUtils.isEmpty(u.toString())) {
                            fastDFSClientWrapper.deleteFile(u.toString());
                        }
                    });
                }
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            if (null != factory){
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean changeSerialNumber(String id, String serialNumber) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(serialNumber)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            // 查询状态标记(0-审批中 1-审批通过 2-草稿) 为审核通过的数据
            int i = mapper.changeSerialNumber(id, serialNumber);
            if (i > 0) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("您所输入的 编号 已存在，请重新输入！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean getProcessData(String ids) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            List<String> list = JSONObject.parseArray(ids, String.class);
            List<Map> planBeans = new LinkedList<>();
            Map map;
            List<ContributoryPlanBeanDetail> details;
            for (String id : list) {
                map = mapper.getProcessData(id);
                if (map == null) {
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                    return msg;
                }
                details = mapper.getDetailById(id);
                map.put("details", details);
                planBeans.add(map);
            }
            msg.setData(planBeans);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public List<Map> queryExportForList(String corpCode, String year, String manager, String statusFlag) {
        List<Map> list = null;
        try (SessionFactory factory = new SessionFactory()) {
            ContributoryPlanMapper mapper = factory.getMapper(ContributoryPlanMapper.class);
            Map map = new HashMap();
            map.put("corpCode", corpCode);
            map.put("year", year);
            map.put("manager", manager);
            // 查询 状态标记(0-审批中 1-审批通过 2-草稿) 不为审批中的数据
            if (StringUtils.isEmpty(statusFlag)) {
                map.put("status_flag_0", STATUS_FLAG_0);
            } else {
                map.put("status_flag", statusFlag);
            }
            // 查询
            list = mapper.queryExportForList(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    /**
     * 保存附件
     *
     * @param files
     * @return 返回附件信息json数据格式
     */
    private String saveFiles(MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return null;
        }
        JSONArray array = new JSONArray();
        JSONObject object;
        for (MultipartFile file : files) {
            object = new JSONObject();
            object.put("filename", file.getOriginalFilename());
            object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
            object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
            array.add(object);
        }
        return JSON.toJSONString(array);
    }

    /**
     * 新增 投入计划明细
     *
     * @param details
     * @param contributoryPlanId 投入计划id
     * @return
     */
    private void insertDetail(List<ContributoryPlanBeanDetail> details, String contributoryPlanId, ContributoryPlanMapper mapper) throws Exception {
        if (details != null && details.size() > 0) {
            for (ContributoryPlanBeanDetail detail : details) {
                detail.setId(DefaultIdGenerator.getInstance().generateLongId());
                detail.setContributoryPlanId(contributoryPlanId);
            }
            // 批量新增
            mapper.insertDetails(details);
        }
    }

    /**
     * 判断map中的 key是否在list中存在
     *
     * @param map
     * @param list
     * @param key
     * @return
     */
    private boolean filter(Map<String, String> map, List<Map> list, String key) {
        String str = map.get(key);
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        if (list == null || list.size() == 0) {
            return false;
        }
        for (Map m : list) {
            if (str.equals(Optional.ofNullable(m.get(key)).get().toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 修改 投入计划明细
     *
     * @param details            投入计划明细
     * @param contributoryPlanId 投入计划id
     */
    private void updateDetails(List<ContributoryPlanBeanDetail> details, String contributoryPlanId, ContributoryPlanMapper mapper) throws Exception {
        if (details != null && details.size() > 0) {
            // 根据 投入计划id 删除 投入计划明细
            mapper.deleteDetailsByConId(contributoryPlanId);
            for (ContributoryPlanBeanDetail personBean : details) {
                personBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                personBean.setContributoryPlanId(contributoryPlanId);
            }
            mapper.insertDetails(details);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        flowManagement.getHandlers().put(this.getClass().getName(), new ContributoryPlanServiceImpl());
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
